<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.png">
  <link rel="mask-icon" href="/images/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"./public/search.xml"};
  </script>

  <meta name="description" content="click look more">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解 Virtual DOM">
<meta property="og:url" content="https://gitee.com/mamba666/mamba666.git/2020/03/12/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3-Virtual-DOM/index.html">
<meta property="og:site_name" content="共你云雨">
<meta property="og:description" content="click look more">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-12T03:48:52.310Z">
<meta property="article:modified_time" content="2020-03-12T11:07:21.408Z">
<meta property="article:author" content="Edison">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/mamba666/mamba666.git/2020/03/12/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3-Virtual-DOM/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>深入理解 Virtual DOM | 共你云雨</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	<a href="https://github.com/mamba666" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">共你云雨</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/mamba666/mamba666.git/2020/03/12/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3-Virtual-DOM/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Edison">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="共你云雨">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入理解 Virtual DOM
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-03-12 11:48:52 / 修改时间：19:07:21" itemprop="dateCreated datePublished" datetime="2020-03-12T11:48:52+08:00">2020-03-12</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%9D%A2%E8%AF%95/" itemprop="url" rel="index"><span itemprop="name">面试</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>click look more</p>
<a id="more"></a>

<h1 id="what’s-virtual-DOM"><a href="#what’s-virtual-DOM" class="headerlink" title="what’s virtual DOM ?"></a>what’s virtual DOM ?</h1><blockquote>
<p>顾名思义，virtual dom即使用JS模拟的一个dom结构，而不是真正的html绘制的dom。听起来可能有点儿绕，举个例子。假设现在有3个dom：a b c。但是现在想删除b，传统怎么做的呢？把abc全干掉，然后插入ac。virtual dom是直接干掉b，不会对ac做任何操作。这样比起来virtual dom简直效率太高了。提高了页面的重绘性能。</p>
</blockquote>
<p>看个栗子：是不是些virtual dom很麻烦？但是要牢记，浏览器最耗费性能的是dom操作！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// dom：</span></span><br><span class="line"><span class="comment">// &lt;ul id="x"&gt;</span></span><br><span class="line"><span class="comment">// 	&lt;li class="y"&gt;1&lt;/li&gt;</span></span><br><span class="line"><span class="comment">// 	&lt;li class="z"&gt;2&lt;/li&gt;</span></span><br><span class="line"><span class="comment">// &lt;/ul&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用js模拟这个dom</span></span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">	<span class="comment">//ul标签</span></span><br><span class="line">	tag:<span class="string">"ul"</span></span><br><span class="line">	<span class="comment">//ul标签的id属性值</span></span><br><span class="line">	attrs:&#123;</span><br><span class="line">		id:<span class="string">"x"</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//ul标签下的子标签</span></span><br><span class="line">	children:[</span><br><span class="line">		&#123;</span><br><span class="line">			tag:<span class="string">"li"</span>,</span><br><span class="line">			attrs:&#123;</span><br><span class="line">				<span class="comment">// 这里为什么不用class呢？因为class是JS的保留字</span></span><br><span class="line">				className:<span class="string">"y"</span></span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="comment">//里面的文本</span></span><br><span class="line">			children:[<span class="string">"1"</span>]</span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			tag:<span class="string">"li"</span>,</span><br><span class="line">			attrs:&#123;</span><br><span class="line">				className:<span class="string">"z"</span></span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="comment">//里面的文本</span></span><br><span class="line">			children:[<span class="string">"2"</span>]</span><br><span class="line">		&#125;</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="Why-does-Virtual-Dom-exist"><a href="#Why-does-Virtual-Dom-exist" class="headerlink" title="Why does Virtual Dom exist ?"></a>Why does Virtual Dom exist ?</h1><blockquote>
<p>其实这个问题在上面已经回答了，做个总结</p>
</blockquote>
<ol>
<li>DOM操作非常“expensive”，使用js效率会更高</li>
<li>尽量可以精准打击，而不是推倒重来</li>
<li>DOM操作项目越复杂，影响就越严重</li>
</ol>
<h1 id="how-to-use"><a href="#how-to-use" class="headerlink" title="how to use ?"></a>how to use ?</h1><blockquote>
<p>virtual dom实际上只是一个标准，或者说是实现这种功能的统称。比如vue、react实现virtual dom的技术都是不一样的，但是解决的问题都是出不多的</p>
</blockquote>
<h2 id="snabbdom"><a href="#snabbdom" class="headerlink" title="snabbdom"></a>snabbdom</h2><p>来看一个流行的开源virtual dom库：snabbdom</p>
<p>官方例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> snabbdom = <span class="built_in">require</span>(<span class="string">'snabbdom'</span>);</span><br><span class="line"><span class="keyword">var</span> patch = snabbdom.init([ <span class="comment">// 使用选中的模块初始化patch函数</span></span><br><span class="line">  <span class="built_in">require</span>(<span class="string">'snabbdom/modules/class'</span>).default, <span class="comment">// 使切换类变得容易</span></span><br><span class="line">  <span class="built_in">require</span>(<span class="string">'snabbdom/modules/props'</span>).default, <span class="comment">// 用于设置DOM元素的属性</span></span><br><span class="line">  <span class="built_in">require</span>(<span class="string">'snabbdom/modules/style'</span>).default, <span class="comment">// 处理带有动画支持的元素样式</span></span><br><span class="line">  <span class="built_in">require</span>(<span class="string">'snabbdom/modules/eventlisteners'</span>).default, <span class="comment">// 事件监听器</span></span><br><span class="line">]);</span><br><span class="line"><span class="keyword">var</span> h = <span class="built_in">require</span>(<span class="string">'snabbdom/h'</span>).default; <span class="comment">// 用于创建virtual node的辅助函数</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 所以读到现在，实际上snabbdom最主要的两个函数就是 patch &amp; h</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取 id 为 container 的dom。注意，此刻为空容器</span></span><br><span class="line"><span class="keyword">var</span> container = <span class="built_in">document</span>.getElementById(<span class="string">'container'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 可以发现 vnode 是使用 h 创建的</span></span><br><span class="line"><span class="comment">// h的参数为： h("dom's id or class or element",&#123;css styles&#125;,[children or innerhtml])</span></span><br><span class="line"><span class="keyword">var</span> vnode = h(<span class="string">'div#container.two.classes'</span>, &#123;<span class="attr">on</span>: &#123;<span class="attr">click</span>: someFn&#125;&#125;, [</span><br><span class="line">  h(<span class="string">'span'</span>, &#123;<span class="attr">style</span>: &#123;<span class="attr">fontWeight</span>: <span class="string">'bold'</span>&#125;&#125;, <span class="string">'This is bold'</span>),</span><br><span class="line">  <span class="string">' and this is just normal text'</span>,</span><br><span class="line">  h(<span class="string">'a'</span>, &#123;<span class="attr">props</span>: &#123;<span class="attr">href</span>: <span class="string">'/foo'</span>&#125;&#125;, <span class="string">'I\'ll take you places!'</span>)</span><br><span class="line">]);</span><br><span class="line"><span class="comment">// Patch into empty DOM element – this modifies the DOM as a side effect</span></span><br><span class="line"><span class="comment">// 这句话不太会翻译，应该是patch插入到空的dom节点-这是修改dom的副作用？</span></span><br><span class="line"><span class="comment">// 看了下面的patch，才发现这个意思是将vnode插入到名为container的空容器中，即修改containner的dom为vnode</span></span><br><span class="line">patch(container, vnode);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> newVnode = h(<span class="string">'div#container.two.classes'</span>, &#123;<span class="attr">on</span>: &#123;<span class="attr">click</span>: anotherEventHandler&#125;&#125;, [</span><br><span class="line">  h(<span class="string">'span'</span>, &#123;<span class="attr">style</span>: &#123;<span class="attr">fontWeight</span>: <span class="string">'normal'</span>, <span class="attr">fontStyle</span>: <span class="string">'italic'</span>&#125;&#125;, <span class="string">'This is now italic type'</span>),</span><br><span class="line">  <span class="string">' and this is still just normal text'</span>,</span><br><span class="line">  h(<span class="string">'a'</span>, &#123;<span class="attr">props</span>: &#123;<span class="attr">href</span>: <span class="string">'/bar'</span>&#125;&#125;, <span class="string">'I\'ll take you places!'</span>)</span><br><span class="line">]);</span><br><span class="line"><span class="comment">// 第二次调用patch</span></span><br><span class="line">patch(vnode, newVnode); <span class="comment">// Snabbdom有效地将旧视图更新为新状态，将vnode替换成newVnode</span></span><br></pre></td></tr></table></figure>

<h1 id="simple-to-understand-the-diff-Algorithm"><a href="#simple-to-understand-the-diff-Algorithm" class="headerlink" title="simple to understand the diff Algorithm"></a>simple to understand the diff Algorithm</h1><blockquote>
<p>简单了解一下</p>
</blockquote>
<h2 id="what’s-diff-algorithm"><a href="#what’s-diff-algorithm" class="headerlink" title="what’s diff algorithm?"></a>what’s diff algorithm?</h2><blockquote>
<p>实际上就是比较两个文件在内容上有什么不同</p>
</blockquote>
<h2 id="why-use-diff-algorithm"><a href="#why-use-diff-algorithm" class="headerlink" title="why use diff algorithm?"></a>why use diff algorithm?</h2><blockquote>
<p>Because dom is very expensive to manipulate，所以需要找到不同点，所以这也是为什么需要diff算法的原因</p>
</blockquote>
<h2 id="the-realization-of-the-diff"><a href="#the-realization-of-the-diff" class="headerlink" title="the realization of the diff"></a>the realization of the diff</h2><blockquote>
<p>根据前面的snabbdom，有两个核心api：h 和 patch。这里只讲patch</p>
</blockquote>
<p>patch的两种用法</p>
<ol>
<li>patch(container,vnode)  这里只关心vnode（即虚拟的dom）是如何生成为真实的dom的</li>
<li>patch(vnode,newNode) 要找出两种区别，然后新增或者减少dom</li>
</ol>
<h3 id="patch-container-vnode"><a href="#patch-container-vnode" class="headerlink" title="patch(container,vnode)"></a>patch(container,vnode)</h3><p>直接上代码，vnode使用上面定义的</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createElement</span>(<span class="params">vnode</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">let</span> tag=vnode.tag</span><br><span class="line">	<span class="comment">// 要注意attrs是element的id或者class   是可以为空的</span></span><br><span class="line">	<span class="keyword">let</span> attrs=vnode.attrs || &#123;&#125;</span><br><span class="line">	<span class="comment">// 这里同上</span></span><br><span class="line">	<span class="keyword">let</span> children=vnode.children || []</span><br><span class="line">	<span class="comment">// 判断是否传入了有效的vnode</span></span><br><span class="line">	<span class="keyword">if</span>(!tag)</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line">	<span class="comment">// 开始</span></span><br><span class="line">	<span class="comment">// 创建一个节点</span></span><br><span class="line">	<span class="keyword">let</span> elem=<span class="built_in">document</span>.createElement(tag)</span><br><span class="line">	<span class="comment">// 创建属性</span></span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">let</span> attrName <span class="keyword">in</span> attrs)&#123;</span><br><span class="line">		<span class="keyword">if</span>(attrs.hasOwnProperty(attrName))&#123;</span><br><span class="line">			elem.setAttributes(attrName,attrs[attrName])</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 创建子元素</span></span><br><span class="line">	children.forEach(<span class="function"><span class="params">childVnode</span>=&gt;</span>&#123;</span><br><span class="line">		<span class="comment">// 关键来了，递归！！！createElement(childVnode)再次调用这个函数</span></span><br><span class="line">		<span class="comment">// 递归说白了就是自己调用自己</span></span><br><span class="line">		<span class="comment">// 这里childVnode是children的元素，即一个对象，所以能使用递归（因为createElement需要传入一个对象）</span></span><br><span class="line">		elem.appendChild(createElement(childVnode))</span><br><span class="line">	&#125;)</span><br><span class="line">	<span class="comment">// 返回这个元素dom</span></span><br><span class="line">	<span class="keyword">return</span> elem</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="for-in-循环"><a href="#for-in-循环" class="headerlink" title="for in 循环"></a>for in 循环</h4><blockquote>
<p>for in是用来遍历对象的，但是不太熟悉，这里在熟悉一下，因为上面的算法用到了</p>
</blockquote>
<p>官方解释：<strong>for…in 语句用于遍历数组或者对象的属性（对数组或者对象的属性进行循环操作）</strong></p>
<p>看个例子</p>
<p>数组：可以发现在遍历数组时，i表示的是每个元素的下标</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i <span class="keyword">in</span> a)&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(i);<span class="comment">//0 1 2</span></span><br><span class="line">	<span class="built_in">console</span>.log(a[i]);<span class="comment">//1 2 3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对象：可以发现在遍历对象时，i是对象的key。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a=&#123;</span><br><span class="line">	x:<span class="number">1</span>,</span><br><span class="line">	y:<span class="number">2</span>,</span><br><span class="line">	z:<span class="number">3</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i <span class="keyword">in</span> a)&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(i);<span class="comment">//x y z</span></span><br><span class="line">	<span class="built_in">console</span>.log(a[i]);<span class="comment">//1 2 3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="for-of-循环"><a href="#for-of-循环" class="headerlink" title="for of 循环"></a>for of 循环</h4><blockquote>
<p>for of  是在 for in 之后推出的，那就有意思了，先来看看for of能干什么</p>
</blockquote>
<p>数组：可以发现i现在是数组的值了，不在是下标</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i <span class="keyword">of</span> a)&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(i);<span class="comment">//1 2 3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对象：怎么是不是觉得i现在变成了对象的value？<strong>oops~  大错特错，因为for of不支持数组！所以这种用法是错误的</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a=&#123;</span><br><span class="line">	x:<span class="number">1</span>,</span><br><span class="line">	y:<span class="number">2</span>,</span><br><span class="line">	z:<span class="number">3</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i <span class="keyword">in</span> a)&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(i);</span><br><span class="line">	<span class="built_in">console</span>.log(a[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><blockquote>
<p>所以，根据代码，for in之后，attrName表示的是标签的class值或者id值。在提取出attrName后，在通过hasOwnProperty进行判断attrName是否为attr的自有属性，如果判断为真，就为elem创建这个属性</p>
</blockquote>
<h4 id="forEach"><a href="#forEach" class="headerlink" title="forEach"></a>forEach</h4><blockquote>
<p>forEach() 方法对数组的每个元素执行一次提供的函数。</p>
</blockquote>
<p>写到这里其实突然想起来一个事儿，就是之前在面试的时候，碰到一个题目。结构跟下面代码差不多，具体忘了。但是肯定是要用到递归的，当时就觉得z里面嵌套了n（未知）层，就觉得很难搞，就凉在这儿了。哎其实就是递归的问题</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a=&#123;</span><br><span class="line">	x:<span class="number">1</span>,</span><br><span class="line">	y:<span class="number">1</span>,</span><br><span class="line">	z:[</span><br><span class="line">		&#123;</span><br><span class="line">			x:<span class="number">2</span>,</span><br><span class="line">			y:<span class="number">2</span>,</span><br><span class="line">			z:[</span><br><span class="line">				&#123;</span><br><span class="line">					x:<span class="number">3</span>,</span><br><span class="line">					y:<span class="number">3</span></span><br><span class="line">				&#125;</span><br><span class="line">			]</span><br><span class="line">		&#125;</span><br><span class="line">	]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> children=a.z</span><br><span class="line"><span class="built_in">console</span>.log(children)<span class="comment">//[ &#123; x: 2, y: 2, z: [ [Object] ] &#125; ]</span></span><br><span class="line">children.forEach(<span class="function"><span class="params">item</span>=&gt;</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(item)<span class="comment">//&#123; x: 2, y: 2, z: [ &#123; x: 3, y: 3 &#125; ] &#125;</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="patch-vnode-newNode"><a href="#patch-vnode-newNode" class="headerlink" title="patch(vnode,newNode)"></a>patch(vnode,newNode)</h3><p>这里只考虑最简单的情况:子节点被修改，并且新增了一个子节点</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateChildren</span>(<span class="params">vnode,newVnode</span>)</span>&#123;</span><br><span class="line">	<span class="comment">//首先将两个子节点都拿出来</span></span><br><span class="line">	<span class="keyword">let</span> children=vnode.children || []</span><br><span class="line">	<span class="keyword">let</span> newChildren=newVnode.children || []</span><br><span class="line"></span><br><span class="line">	<span class="comment">//遍历现有的vnode</span></span><br><span class="line">	<span class="comment">//index为forEach的可选参数，即当前元素的索引</span></span><br><span class="line">	children.forEach(<span class="function">(<span class="params">item,index</span>)=&gt;</span>&#123;</span><br><span class="line">		<span class="comment">//遍历新的vnode</span></span><br><span class="line">		<span class="keyword">let</span> newChild=newChildren[index]</span><br><span class="line">		<span class="comment">//如果不存在</span></span><br><span class="line">		<span class="keyword">if</span>(newChild==<span class="literal">null</span>)</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		<span class="comment">//如果旧的vnode的tag等于新的,就递归</span></span><br><span class="line">		<span class="keyword">if</span>(item.tag===newChild.tag)&#123;</span><br><span class="line">			updateChildren(item,newChild)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"># js</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/11/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3JS%E5%BC%82%E6%AD%A5/" rel="prev" title="深入理解JS异步">
      <i class="fa fa-chevron-left"></i> 深入理解JS异步
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/03/13/BFC%EF%BC%88Block-Formatting-Context%EF%BC%89/" rel="next" title="BFC（Block Formatting Context）">
      BFC（Block Formatting Context） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#what’s-virtual-DOM"><span class="nav-number">1.</span> <span class="nav-text">what’s virtual DOM ?</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Why-does-Virtual-Dom-exist"><span class="nav-number">2.</span> <span class="nav-text">Why does Virtual Dom exist ?</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#how-to-use"><span class="nav-number">3.</span> <span class="nav-text">how to use ?</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#snabbdom"><span class="nav-number">3.1.</span> <span class="nav-text">snabbdom</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#simple-to-understand-the-diff-Algorithm"><span class="nav-number">4.</span> <span class="nav-text">simple to understand the diff Algorithm</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#what’s-diff-algorithm"><span class="nav-number">4.1.</span> <span class="nav-text">what’s diff algorithm?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#why-use-diff-algorithm"><span class="nav-number">4.2.</span> <span class="nav-text">why use diff algorithm?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#the-realization-of-the-diff"><span class="nav-number">4.3.</span> <span class="nav-text">the realization of the diff</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#patch-container-vnode"><span class="nav-number">4.3.1.</span> <span class="nav-text">patch(container,vnode)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#for-in-循环"><span class="nav-number">4.3.1.1.</span> <span class="nav-text">for in 循环</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#for-of-循环"><span class="nav-number">4.3.1.2.</span> <span class="nav-text">for of 循环</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#总结"><span class="nav-number">4.3.1.2.1.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#forEach"><span class="nav-number">4.3.1.3.</span> <span class="nav-text">forEach</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#patch-vnode-newNode"><span class="nav-number">4.3.2.</span> <span class="nav-text">patch(vnode,newNode)</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Edison</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">124</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
</div>
  <div class="powered-by">山高水远  一定相见
  </div>
<div></div>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">至今已写107.1k字</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
